package net.sf.xoperator.startup;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import net.sf.xoperator.Constants;
import net.sf.xoperator.xmpp.AccountInfo;

public class PropertiesMain extends CommandLineMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		PropertiesMain main = new PropertiesMain();

		main.startUp(args);
		int exit = 0;
		try {
			while (exit!=-1) {
				exit = System.in.read();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	@Override
	public void startUp(String[] args) {
		Properties props = new Properties();
		if(args.length==0){
			//use the xoperator.properties file
			try {
				props.load(new FileInputStream("xoperator.properties"));
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			
		}else if(args.length==1){
			//use the user defined properties file
			try{
				props.load(new FileInputStream(args[0]));
				
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			
		}else{
			System.out.println("Invalid properties count, please recheck parameters.");
			System.exit(1);
		}
		// we assume main is always there
		AccountInfo main = createMainAccount(props);
		
		// if not standalone, there has to be an proxy account
		
		AccountInfo proxy =null;
		if(!Boolean.parseBoolean(props.getProperty("standalone"))){
			proxy = createProxyAccount(props);
		}
		
		
		
		createAndRegisterApplication(main, proxy);
		
		
		
		
	}

	private AccountInfo createProxyAccount(Properties props) {
		AccountInfo proxy = new AccountInfo();
		proxy.setMainAccount(false);
		proxy.setUsername(props.getProperty("proxy_username"));
		proxy.setPassword(props.getProperty("proxy_password"));
		proxy.setServer(props.getProperty("proxy_server"));
		proxy.setPort(props.getProperty("proxy_port")!=null?Integer.parseInt(props.getProperty("proxy_port")):Constants.DEFAULT_JABBER_PORT);
		return proxy;
	}

	private AccountInfo createMainAccount(Properties props) {
		AccountInfo main = new AccountInfo();
		main.setMainAccount(true);
		main.setUsername(props.getProperty("main_username"));
		main.setPassword(props.getProperty("main_password"));
		main.setServer(props.getProperty("main_server"));
		main.setPort(props.getProperty("main_port")!=null?Integer.parseInt(props.getProperty("main_port")):Constants.DEFAULT_JABBER_PORT);
		main.setStandalone(Boolean.parseBoolean(props.getProperty("standalone")));
		return main;

	}

}
